import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mirac
 * Date: 2025-11-28
 * Time: 15:51
 */
public class MyTimer {

    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>(new Comparator<MyTimerTask>() {
        @Override
        public int compare(MyTimerTask o1, MyTimerTask o2) {
            //我们要构建小根堆，所以：
            return (int) (o1.getTime()-o2.getTime());
        }
    });
    //创建一个锁对象
    private Object locker = new Object();

    public MyTimer() {
        //创建一个线程否则执行任务
        Thread thread = new Thread(() -> {
           //它要不断的尝试获取和执行任务
           while (true) {
               synchronized (locker) {
                   while (queue.isEmpty()) {
                       try {
                           locker.wait();
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                   }
                   MyTimerTask task = queue.peek();
                   //查看是否达到执行任务的时间
                   if (System.currentTimeMillis() < task.getTime()) {
                       try {
                           locker.wait(task.getTime()-System.currentTimeMillis());
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                   }else {
                       task.toRun();
                       queue.poll();
                   }
               }
           }
        });
        thread.start();
    }

    public void schedule(Runnable runnable,long delay) {
        synchronized (locker) {
            MyTimerTask task = new MyTimerTask(runnable,System.currentTimeMillis()+delay);
            queue.offer(task);
            locker.notify();
        }
    }
}
